package com.wl.index.Controller;


import org.springframework.core.io.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/files")
public class FileAccessController {
    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("classpath:static/")
    private Resource staticResource;

    @GetMapping("/{filename:.+}")
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        try {
            Path filePath;
            Resource resource;

            // 处理旧图片路径 (img/xxx)
            if (filename.startsWith("img/")) {
                resource = staticResource.createRelative(filename);
            }
            // 处理新上传文件
            else {
                filePath = Paths.get(uploadDir).resolve(filename).normalize();
                resource = new UrlResource(filePath.toUri());
            }

            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_TYPE,
                                Files.probeContentType(Paths.get(resource.getURI())))
                        .body(resource);
            }
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}